﻿using System;
using System.ComponentModel;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace M4W.Limber
{
    [ToolboxItemAttribute(false)]
    public class LimberWP : System.Web.UI.WebControls.WebParts.WebPart
    {
        // Web Part Parameters

        String wp_m4wList = "Announcements";

        [Personalizable()]
        public String m4wListUrl
        {
            get { return wp_m4wList; }
            set { wp_m4wList = value; }
        }

        String wp_m4wNrItems = "4";

        [Personalizable()]
        public String m4wNrItems
        {
            get { return wp_m4wNrItems; }
            set { wp_m4wNrItems = value; }
        }

        String wp_m4wOrder = "By ID Ascending";

        [Personalizable()]
        public String m4wOrder
        {
            get { return wp_m4wOrder; }
            set { wp_m4wOrder = value; }
        }

        String wp_m4wFields = "Title;Body";

        [Personalizable()]
        public String m4wFields
        {
            get { return wp_m4wFields; }
            set { wp_m4wFields = value; }
        }

        protected override void CreateChildControls()
        {
            this.Controls.Add(new LiteralControl("<br />"));

            // Get List

            SPList m4wList = m4wGetList(m4wListUrl);

            if (m4wList == null)
            {
                this.Controls.Add(new LiteralControl(string.Format("List '{0}' is not found. Please check the web part configuration.", (object)m4wListUrl)));
                return;
            }

            // Render menu4web

            String m4wSiteCollUrl = SPContext.Current.Site.Url.ToString();
            this.Controls.Add(new LiteralControl(string.Format("<script src='{0}/Lists/m4w/m4w.js'></script>", (object)m4wSiteCollUrl)));
            this.Controls.Add(new LiteralControl(string.Format("<script src='{0}/Lists/m4w/m4w.limber.js'></script>", (object)m4wSiteCollUrl)));
            this.Controls.Add(new LiteralControl(string.Format("<div style='display: none;'><img src='{0}/Lists/m4w/iadg.gif'><img src='{0}/Lists/m4w/iadb.gif'></div>", (object)m4wSiteCollUrl)));

            // List Fields and Query

            String m4wListViewFields = "";
            string[] m4wListFields = m4wFields.Split(';');
            SPQuery m4wListQuery;
            SPListItemCollection m4wItems;
            String m4wFieldTitle;
            String m4wFieldBody;

            switch (m4wListFields.Length)
            {
                case 2:
                    m4wFieldTitle = m4wListFields[0];
                    m4wFieldBody = m4wListFields[1];
                    m4wListViewFields = "<FieldRef Name='" + m4wFieldTitle + "' /><FieldRef Name='" + m4wFieldBody + "' />";
                    break;
                default:
                    m4wFieldTitle = "Title";
                    m4wFieldBody = "Body";
                    m4wListViewFields = "<FieldRef Name='Title' /><FieldRef Name='Body' />";
                    break;
            }

            m4wListQuery = new SPQuery();
            m4wListQuery.ViewFields = m4wListViewFields;
            m4wListQuery.ViewFieldsOnly = true;

            // Sort Order

            switch (m4wOrder)
            {
                case "By ID Ascending":
                    m4wListQuery.Query = "<OrderBy><FieldRef Name='ID' Ascending='True' /></OrderBy>";
                    break;
                case "By ID Descending":
                    m4wListQuery.Query = "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
                    break;
                case "By Modified Ascending":
                    m4wListQuery.Query = "<OrderBy><FieldRef Name='Modified' Ascending='True' /></OrderBy>";
                    break;
                case "By Modified Descending":
                    m4wListQuery.Query = "<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy>";
                    break;
                default:
                    m4wListQuery.Query = "<OrderBy><FieldRef Name='ID' Ascending='True' /></OrderBy>";
                    break;
            }

            m4wListQuery.RowLimit = 10;

            m4wItems = m4wList.GetItems(m4wListQuery);

            try
            {
                String listItemTitle = m4wItems[0][m4wFieldTitle].ToString();
                String listItemBody = m4wItems[0][m4wFieldBody].ToString();
            }
            catch (Exception)
            {
                this.Controls.Add(new LiteralControl(string.Format("List '{0}' fields '{1}' could not be retrieved. Please make sure that the list is not empty and verify the fields.", (object)m4wListUrl, (object)m4wFields)));
                return;
            }

            // Menu

            String m4wMenu;
            m4wMenu = this.ID.ToString();
            m4wMenu = m4wMenu.Replace("_", "");

            this.Controls.Add(new LiteralControl(string.Format("<table id='menu4web_{0}' class='m4wLT' cellpadding='0' cellspacing='0' width='100%' height='100%'>", (object)m4wMenu)));
            this.Controls.Add(new LiteralControl("<tr><td class='m4wLTD'><script>"));

            String m4wLId = "";

            for (int i = 0; i < Int16.Parse(m4wNrItems) && i < m4wItems.Count; i++)
            {
                m4wLId = i.ToString();

                String listItemTitle = m4wItems[i][m4wFieldTitle].ToString();
                listItemTitle = m4wPrepareString(listItemTitle);

                this.Controls.Add(new LiteralControl(string.Format("m4w.id='{0}_1{1}0';", (object)m4wMenu, (object)m4wLId)));
                this.Controls.Add(new LiteralControl("m4w.mLC(m4w.id);"));
                this.Controls.Add(new LiteralControl(string.Format("m4w.iLC(m4w.id, '{0}_1{1}1');", (object)m4wMenu, (object)m4wLId)));
                this.Controls.Add(new LiteralControl(string.Format("m4w.eLC(m4w.id, '{0}', '{1}');", (object)listItemTitle, (object)m4wSiteCollUrl)));
                this.Controls.Add(new LiteralControl("m4w.draw();"));

                String listItemBody = m4wItems[i][m4wFieldBody].ToString();
                listItemBody = m4wPrepareString(listItemBody);

                this.Controls.Add(new LiteralControl(string.Format("m4w.id='{0}_1{1}1';", (object)m4wMenu, (object)m4wLId)));
                this.Controls.Add(new LiteralControl("m4w.mLD(m4w.id);"));
                this.Controls.Add(new LiteralControl("m4w.iLD(m4w.id);"));
                this.Controls.Add(new LiteralControl(string.Format("m4w.eLD(m4w.id, '{0}');", (object)listItemBody)));
                this.Controls.Add(new LiteralControl("m4w.draw();"));
            }

            this.Controls.Add(new LiteralControl("</script></td></tr>"));
            this.Controls.Add(new LiteralControl("</table>"));
        }

        // Get List

        private SPList m4wGetList(String m4wListText)
        {
            SPList m4wListRef = null;

            try
            {
                m4wListRef = SPContext.Current.Web.Lists[m4wListText];
            }
            catch (Exception)
            {
            }

            try
            {
                if (m4wListRef == null)
                {
                    m4wListRef = SPContext.Current.Web.GetList(m4wListText);
                }
            }
            catch (Exception)
            {
            }

            try
            {
                if (m4wListRef == null)
                {
                    String m4wSiteUrl;
                    String m4wSiteServerUrl;
                    String m4wSiteRelativeUrl;
                    String m4wListRelativeUrl;
                    String m4wWebUrl;

                    m4wSiteUrl = m4wListText.Substring(0, m4wListText.LastIndexOf("/Lists/"));

                    using (SPSite m4wSite = new SPSite(m4wSiteUrl))
                    {
                        m4wSiteServerUrl = m4wSite.RootWeb.Url.ToString();
                        m4wSiteRelativeUrl = m4wSite.ServerRelativeUrl.ToString();
                        m4wListRelativeUrl = m4wListText.Replace(m4wSiteServerUrl, "");
                        if (m4wSiteRelativeUrl != "/")
                        {
                            m4wListRelativeUrl = m4wSiteRelativeUrl + m4wListRelativeUrl;
                        }

                        m4wWebUrl = m4wListRelativeUrl.Substring(0, m4wListRelativeUrl.LastIndexOf("/Lists/"));

                        using (SPWeb m4wWeb = m4wSite.OpenWeb(m4wWebUrl))
                        {
                            m4wListRef = m4wWeb.GetList(m4wListRelativeUrl);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return m4wListRef;
        }

        // Remove Line Breaks and Escape Quotes

        private String m4wPrepareString(String m4wString)
        {
            m4wString = m4wString.Replace(System.Environment.NewLine, "");
            m4wString = m4wString.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
            m4wString = m4wString.Replace("  ", " ").Replace("  ", " ").Replace("  ", " ");
            m4wString = m4wString.Replace("'", "\\'");

            return m4wString;
        }

        // Create Editor Part

        public override EditorPartCollection CreateEditorParts()
        {
            ArrayList editorArray = new ArrayList();
            LimberEP ep = new LimberEP();
            ep.ID = this.ID + "_EP";
            editorArray.Add(ep);
            EditorPartCollection editorParts = new EditorPartCollection(editorArray);
            return editorParts;
        }
    }
}